package cn.fl.risknew.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cmm.mid.core.framework.page.KeyValueVO;
import cmm.user.facade.system.api.ISysOrgApiService;
import cmm.user.facade.system.condition.SysOrgQueryCondition;
import cmm.user.facade.system.dto.SysOrgDTO;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.constant.DictionaryConstant;
import cn.fl.overdue.dto.*;
import cn.fl.ref.fribaseinfo.transform.FriBaseInfoVOTransform;
import cn.fl.system.service.ISysOrgService;
import com.alibaba.fastjson.JSON;
import fl.customer.facade.customer.api.ICustomerApiService;
import fl.customer.facade.customer.condition.CstBscInfoQueryCondition;
import fl.customer.facade.customer.dto.CstBscInfoDTO;
import fl.flow.facade.flow.constant.FlowConstant;
import fl.flow.facade.flow.dto.FlowStartParamsDTO;
import fl.ref.fribaseinfo.dto.FriBaseInfoDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.api.ISysUsrApiService;
import cmm.user.facade.system.condition.SysUsrQueryCondition;
import cmm.user.facade.system.dto.SysUsrDTO;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.overdue.condition.OverdueBaseCondition;
import cn.fl.overdue.condition.OverdueContractQueryCondition;
import cn.fl.overdue.condition.OverduePaySchQueryCondition;
import cn.fl.overdue.service.IOverdueApiService;
import cn.fl.payschd.dto.PaySchDDTO;
import cn.fl.project.service.IPrjPrdPaySchMService;
import cn.fl.project.vo.PrjPrdPaySchMVO;
import cn.fl.ref.fribaseinfo.service.IFriBaseInfoService;
import cn.fl.ref.fribaseinfo.vo.FriBaseInfoVO;
import cn.fl.risknew.condition.RskUsrCstRQueryCondition;
import cn.fl.risknew.dto.RskUsrCstRDTO;
import cn.fl.risknew.constant.RiskConstant;
import cn.fl.risknew.service.IRiskOverdueService;
import cn.fl.risknew.service.IRskUsrCstRNewApiService;
import cn.fl.risknew.transform.OverdueCapFundVOTransform;
import cn.fl.risknew.transform.OverdueCapFundVfDtlVOTransform;
import cn.fl.risknew.transform.OverdueContractVOTransform;
import cn.fl.risknew.transform.OverdueCstVOTransform;
import cn.fl.risknew.transform.OverduePaySchVOTransform;
import cn.fl.risknew.transform.OverduepayschDVOTransform;
import cn.fl.risknew.vo.OverdueCapFundVO;
import cn.fl.risknew.vo.OverdueCapFundVfDtlVO;
import cn.fl.risknew.vo.OverdueContractVO;
import cn.fl.risknew.vo.OverdueCstVO;
import cn.fl.risknew.vo.OverduePaySchDVO;
import cn.fl.risknew.vo.OverduePaySchVO;
import fl.ref.fribaseinfo.condition.FriBaseInfoQueryCondition;
import fl.ref.fribaseinfo.constant.FriBaseInfoConstant;

/**
 *  逾期催收服务
 * 作者:hongyanbo
 * 时间:2018/8/20
 */
@Service
public class RiskOverdueServiceImpl implements IRiskOverdueService {
    public static final Logger LOGGER = LoggerFactory.getLogger(RiskOverdueServiceImpl.class);

    @Autowired
    private IFriBaseInfoService friBaseInfoService;//融资机构基础信息表
    @Autowired
    private IOverdueApiService overdueApiService;
    @Autowired
    private IPrjPrdPaySchMService paySchMService;
    /**
     * 数据字典服务
     */
    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;
    @Autowired
    private IPrjPrdPaySchMService prjPrdPaySchMService;
    @Autowired
    private IRskUsrCstRNewApiService rskUsrCstRNewApiService;
    @Autowired
    private ISysUsrApiService sysUsrApiService;
    @Autowired
    private ISysOrgApiService sysOrgApiService;
    @Autowired
    private ICustomerApiService customerApiService;

    public List<FriBaseInfoVO> getFriBaseInfoList() {
        Pager page = new Pager();
        page.setCurrentPage(1);
        page.setEveryPage(Integer.MAX_VALUE);
        FriBaseInfoQueryCondition qc = new FriBaseInfoQueryCondition();
        qc.setInsSts(FriBaseInfoConstant.FRI_BASE_INFO_INS_STS_PASS);
        qc.setInsUseCd("2");
        qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
        qc.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
        page.setCondition(qc);
        Pager pager = this.friBaseInfoService.searchListPage(page);
        return FriBaseInfoVOTransform.toVOList((List<FriBaseInfoDTO>) pager.getResultList());
    }

    @Override
    public List<OverdueContractVO> getOverdueContractList(OverdueContractQueryCondition condition) {
        List<OverdueContractDTO> overdueContractDTOS = overdueApiService.selectOverdueContractList(condition);
        // SUE0007转码
        Map<String, String> sue0007 = this.sysDictionaryApiService.searchGroupToMap("11000", "0000", "SUE0007");
        // orgCd转码
        List<String> orgCdList = new ArrayList<>();
        for (OverdueContractDTO overdueContractDTO : overdueContractDTOS) {
            orgCdList.add(overdueContractDTO.getBuOrgCd());
        }
        if(CollectionUtils.isNotEmpty(orgCdList)){
            SysOrgQueryCondition qc =new SysOrgQueryCondition();
            qc.setOrgCdList(orgCdList);
            List<SysOrgDTO> sysOrgDTOS = sysOrgApiService.searchSysOrgList(qc);
            // toMap
            Map<String,String> orgCdNmMap = new HashMap<>();
            if(CollectionUtils.isNotEmpty(sysOrgDTOS)){
                for (SysOrgDTO sysOrgDTO : sysOrgDTOS) {
                    orgCdNmMap.put(sysOrgDTO.getOrgCd(),sysOrgDTO.getOrgNm());
                }
                // setDto
                for (OverdueContractDTO overdueContractDTO : overdueContractDTOS) {
                    String buOrgCd = overdueContractDTO.getBuOrgCd();
                    overdueContractDTO.setBuOrgCd(orgCdNmMap.get(buOrgCd));
                    String sueStsCd = overdueContractDTO.getSueStsCd();
                    if(StringUtils.isNotBlank(sueStsCd)){
                        overdueContractDTO.setSueStsCd(sue0007.get(sueStsCd));
                    }
                }
            }
        }



        return OverdueContractVOTransform.toVOList(overdueContractDTOS);
    }

    @Override
    public List<OverduePaySchVO> getOverduePaySchList(OverduePaySchQueryCondition condition) {
        List<OverduePaySchDTO> overduePaySchDTOS = overdueApiService.selectOverduePaySchList(condition);
        // 资产状态转码
        Map<String, String> prj0037 = this.sysDictionaryApiService.searchGroupToMapAll("11000", "0000", "PRJ0037");
        for (OverduePaySchDTO overduePaySchDTO : overduePaySchDTOS) {
            String prdStsCd = overduePaySchDTO.getPrdStsCd();
            if(StringUtils.isNotBlank(prdStsCd)){
                String val = prj0037.get(prdStsCd);
                overduePaySchDTO.setPrdStsCd(val);
            }
        }
        return OverduePaySchVOTransform.toVOList(overduePaySchDTOS);
    }

    @Override
    public Pager cstOverdueCapFundListPage(Pager pager) {

        pager = overdueApiService.selectOverdueCapFundListPage(pager);
        List<OverdueCapFundDTO> resultList = (List<OverdueCapFundDTO>) pager.getResultList();
        List<OverdueCapFundVO> overdueCapFundVOS = OverdueCapFundVOTransform.toVOList(resultList);
        pager.setResultList(overdueCapFundVOS);
        return pager;
    }

    @Override
    public Pager selectOverduePaySchDS01ListPage(Pager pager) {
        pager = overdueApiService.selectOverduePaySchDS01ListPage(pager);
        List<PaySchDDTO> resultList = (List<PaySchDDTO>) pager.getResultList();
        if(CollectionUtils.isNotEmpty(resultList)){
            Date currentDate = new Date();
            List<OverduePaySchDVO> overduePaySchDVOS = OverduepayschDVOTransform.toVOList(resultList);
            for (OverduePaySchDVO overduePaySchDVO : overduePaySchDVOS) {
                // 计算逾期天数
                Date payDt = overduePaySchDVO.getPayDt();
                long daysBetweenTwoDates = DateUtils.getDaysBetweenTwoDates(payDt, currentDate);
                 overduePaySchDVO.setOvdDays(daysBetweenTwoDates);
                // 获取支付表编号
            }
            pager.setResultList(overduePaySchDVOS);
        }
        return pager;
    }

	@SuppressWarnings("unchecked")
	@Override
	public Pager selectOverduePaySchDS01AndFEEListPage(Pager pager,String tableNm) {
		pager = overdueApiService.selectOverduePaySchDS01AndFEEListPage(pager,tableNm);
        List<PaySchDDTO> resultList = (List<PaySchDDTO>) pager.getResultList();
        if(CollectionUtils.isNotEmpty(resultList)){
        	Map<String, String> feeTypCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), RiskConstant.CODE_FEE_TYP_CD_GRP);
            Date currentDate = new Date();
            List<OverduePaySchDVO> overduePaySchDVOS = OverduepayschDVOTransform.toVOList(resultList);
            for (OverduePaySchDVO overduePaySchDVO : overduePaySchDVOS) {
                // 计算逾期天数
                Date payDt = overduePaySchDVO.getPayDt();
                Date vfDt = overduePaySchDVO.getVfDt();
                if(vfDt!=null){
                	long daysBetweenTwoDates = DateUtils.getDaysBetweenTwoDates(payDt, vfDt);
                    overduePaySchDVO.setOvdDays(daysBetweenTwoDates);
                }else{
                	long daysBetweenTwoDates = DateUtils.getDaysBetweenTwoDates(payDt, currentDate);
                    overduePaySchDVO.setOvdDays(daysBetweenTwoDates);
                }
                
                // 获取支付表编号
                PrjPrdPaySchMVO prjPrdPaySchMVO = paySchMService.selectById(overduePaySchDVO.getPaySchId());
                overduePaySchDVO.setPaySchNo(prjPrdPaySchMVO.getPaySchNo());
                //设置费用类型名称
                if(feeTypCdMap!=null&&feeTypCdMap.containsKey(overduePaySchDVO.getFeeTypCd())){
                	overduePaySchDVO.setFeeTypCdNm(feeTypCdMap.get(overduePaySchDVO.getFeeTypCd()));
                }
            }
            pager.setResultList(overduePaySchDVOS);
        }
        return pager;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pager selectOverdueFundVfDtlListPage(Pager pager) {
		pager = this.overdueApiService.selectOverdueFundVfDtlListPage(pager);
		List<OverdueCapFundVfDtlDTO> resultList = (List<OverdueCapFundVfDtlDTO>)pager.getResultList();
		if(CollectionUtils.isNotEmpty(resultList)){
			Map<String, String> feeTypCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), RiskConstant.CODE_FEE_TYP_CD_GRP);
			List<OverdueCapFundVfDtlVO> resultVOList = OverdueCapFundVfDtlVOTransform.toVOList(resultList);
			for(OverdueCapFundVfDtlVO vo:resultVOList){
				 if(feeTypCdMap!=null&&feeTypCdMap.containsKey(vo.getFeeTypCd())){
					 vo.setFeeTypCdNm(feeTypCdMap.get(vo.getFeeTypCd()));
	             }
			}
			pager.setResultList(resultVOList);
		}
		return pager;
	}

    @Override
    public Pager getOverdueCustomerListPage(OverdueBaseCondition condition, int page, int pagesize) {
        Pager pager = new Pager();
        pager.setCondition(condition);
        pager.setEveryPage(pagesize);
        pager.setCurrentPage(page);
        if(StringUtils.isNotBlank(condition.getCertNo())){
            CstBscInfoQueryCondition qc = new CstBscInfoQueryCondition();
            qc.setSysCd("11000");
            qc.setBuOrgCd("0000");
            qc.setOrgCd("0000");
            qc.setCertNo(condition.getCertNo());
            List<CstBscInfoDTO> list = this.customerApiService.searchListByCon(qc);
            if(CollectionUtils.isNotEmpty(list)){
                Long id = list.get(0).getId();
                condition.setCstId(id);
            }
        }
        pager = this.overdueApiService.selectOverdueCstListPage(pager);
        List<OverdueCstDTO> resultList = (List<OverdueCstDTO>) pager.getResultList();
        pager.setResultList(OverdueCstVOTransform.toVOList(resultList));

        return pager;
    }

    @Override
    public Pager initMyTaskPage(Pager pager) {
        pager = this.overdueApiService.selectMyTaskPage(pager);
        // transformVOs
        List<OverdueCstDTO> resultList = (List<OverdueCstDTO>) pager.getResultList();
        if(CollectionUtils.isNotEmpty(resultList)){
            List<OverdueCstVO> overdueCstVOS = OverdueCstVOTransform.toVOList(resultList);
            pager.setResultList(overdueCstVOS);
        }
        return pager;
    }

	@Override
	@Deprecated
	public Map<String,Object> getfinalPayAmt(Long paySchId,String tableNm,Long ovdAmt,Long fineAmt) {
		Map<String,Object> finalPayMap=new HashMap<String, Object>();
		Long stlAmt = 0L;
		String buOrgCd = "";
		if(tableNm!=null&&tableNm.equals("PRJ_PRD_PAY_SCH_M")){
			PrjPrdPaySchMVO pay =this.prjPrdPaySchMService.selectById(paySchId);
			if(pay!=null){
				buOrgCd = pay.getBuOrgCd();
			}
		}
		OverdueBaseCondition condition = new OverdueBaseCondition();
		condition.setPaySchId(paySchId);
		condition.setTableNm(tableNm);
		condition.setBuOrgCd(buOrgCd);
		condition.setOvdAmt(ovdAmt);
		condition.setFineAmt(fineAmt);
//		stlAmt = this.overdueApiService.getfinalPayAmt(condition);
		finalPayMap.put("stlAmt", stlAmt);
		finalPayMap.put("buOrgCd", buOrgCd);
		return finalPayMap;
	}

    @Override
    public DataResultVO exportOverdueExcel(OverdueBaseCondition condition) {
        DataResultVO vo = new DataResultVO();
        try {
            String url = this.overdueApiService.exportOverdueExcel(condition);
            vo.setSuccess(1);
            vo.setInfo("导出成功");
            vo.setData(url);
        }catch (Exception e){
            vo.setSuccess(0);
            vo.setInfo("数据量过大超时");
            vo.setData(null);
            BaseLogUtils.error(LOGGER,"exportOverdueExcel",e.getMessage());
        }
        return vo;
    }

    @Override
    public DataResultVO exportMyTaskExcel(OverdueBaseCondition condition) {
        condition.setUsrId(CurrentThreadContext.getCurrentUserId());
        DataResultVO vo = new DataResultVO();
        String url = this.overdueApiService.exportMyTaskExcel(condition);
        vo.setSuccess(1);
        vo.setInfo("导出成功");
        vo.setData(url);
        return vo;
    }

	@Override
	public Pager getTaskOverdueCustomerListPage(OverdueBaseCondition condition,
			int page, int pagesize) {
		Pager pager = new Pager();
        pager.setCondition(condition);
        pager.setEveryPage(pagesize);
        pager.setCurrentPage(page);
        pager = this.overdueApiService.selectOverdueCstListPage(pager);
        List<OverdueCstDTO> resultList = (List<OverdueCstDTO>) pager.getResultList();
        List<OverdueCstVO> voList = null;
        if(CollectionUtils.isNotEmpty(resultList)){
        	voList = OverdueCstVOTransform.toVOList(resultList);
        	List<Long> cstIdList = null;
        	Map<Long, SysUsrDTO> cstUsrMap = new HashMap<>();//客户ID:用户
        	cstIdList = new ArrayList<Long>(voList.size());
            for (OverdueCstVO vo : voList) {
                cstIdList.add(Long.valueOf(vo.getCstId()));
            }
            //查询客户分配的责任人
            RskUsrCstRQueryCondition usrCstRQueryCondition = new RskUsrCstRQueryCondition();
            usrCstRQueryCondition.setCstIdList(cstIdList);
            usrCstRQueryCondition.setIsDel(0);
            usrCstRQueryCondition.setIsValid(1);
            List<RskUsrCstRDTO> rList = this.rskUsrCstRNewApiService.searchRskUsrCstRList(usrCstRQueryCondition);
            if (CollectionUtils.isNotEmpty(rList)) {
                Map<Long, Long> cstMap = new HashMap<Long, Long>(rList.size());
                List<Long> usrIdList=new ArrayList<>(rList.size());
                for (RskUsrCstRDTO usrCstRDTO : rList) {
                    cstMap.put(usrCstRDTO.getCstId(), usrCstRDTO.getUsrId());
                    if(usrIdList.contains(usrCstRDTO.getUsrId())){
                        continue;
                    }
                    usrIdList.add(usrCstRDTO.getUsrId());
                }
               
                SysUsrQueryCondition sysUsrQueryCondition = new SysUsrQueryCondition();
                sysUsrQueryCondition.setUsrIds(usrIdList);
                sysUsrQueryCondition.setSysCd(CurrentThreadContext.getCurrentSysCd());
                List<SysUsrDTO> usrList = sysUsrApiService.searchSysUsrList(sysUsrQueryCondition);
                Map<Long, SysUsrDTO> usrMap = null;
                if (CollectionUtils.isNotEmpty(usrList)) {
                    usrMap = new HashMap<>(usrList.size());
                    for (SysUsrDTO dto : usrList) {
                        usrMap.put(dto.getId(), dto);
                    }
                }

                for (Map.Entry<Long, Long> entry : cstMap.entrySet()) {
                    if (usrMap != null && usrMap.containsKey(entry.getValue())) {
                        cstUsrMap.put(entry.getKey(), usrMap.get(entry.getValue()));
                    }
                }
            }
            for (OverdueCstVO vo : voList) {
                if (cstUsrMap != null && cstUsrMap.containsKey(Long.valueOf(vo.getCstId()))) {               	
                    vo.setUsrNm(cstUsrMap.get(Long.valueOf(vo.getCstId())).getRefRlNm());
                    vo.setUsrId(cstUsrMap.get(Long.valueOf(vo.getCstId())).getId());
                }
            }
        }       
        pager.setResultList(voList);
        return pager;
	}

    @Override
    public OverdueCstVO getSum(OverdueBaseCondition condition) {
        return OverdueCstVOTransform.toVO(this.overdueApiService.getSum(condition));
    }

    @Override
    public OverdueCstVO getMyTaskSum(OverdueBaseCondition condition) {
        return OverdueCstVOTransform.toVO(this.overdueApiService.getMyTaskSum(condition));
    }

    /**
     * 获取流程发起对象 传到service层调用flowApiService.noTransFlowStart方法发起流程
     * @param orgCd 业务数据所属客户经理组织架构
     * @param buOrgCd 业务数据所属事业部
     * @param modelTypCd 流程业务分类(FS01 File Supply 文件补充)
     * @param rskFileId 流程业务数据ID
     * @param tabNm 业务数据表名
     * @return
     */
    @Override
    public FlowStartParamsDTO getFlowStartParamsDTO(String orgCd, String buOrgCd, String modelTypCd, Long rskFileId,String tabNm) {

        FlowStartParamsDTO flowStartParamsDTO = new FlowStartParamsDTO();
        flowStartParamsDTO.setAudStsCd(FlowConstant.FLOW_CHECK_STATE_IN);
        flowStartParamsDTO.setWordsInTheTable("PRJ");
        //flowStartParamsDTO.setProcDefKey(procDefKey);
        //flowStartParamsDTO.setProcDefId(procDefId);
        //flowStartParamsDTO.setProcNo(procNo);
        flowStartParamsDTO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
        flowStartParamsDTO.setBusinessKey(String.valueOf(rskFileId));
        flowStartParamsDTO.setOrgCd(orgCd);
        flowStartParamsDTO.setSysCd(CurrentThreadContext.getFlServiceSysCd());
        flowStartParamsDTO.setBuOrgCd(buOrgCd);
        flowStartParamsDTO.setInitiator(String.valueOf(CurrentThreadContext.getCurrentUserId()));
        flowStartParamsDTO.setInitiatorNm(CurrentThreadContext.getCurrentUserName());
        flowStartParamsDTO.setProcPriority(FlowConstant.FLOW_PRIORITY_EMERGENCY);
        flowStartParamsDTO.setBusinessType(tabNm);
        flowStartParamsDTO.setModelTyp(modelTypCd);
        return flowStartParamsDTO;
    }

    @Override
    public Pager selectGroupTaskListPage(OverdueBaseCondition condition, int page, int pagesize) {
        Pager pager = new Pager();
        pager.setCondition(condition);
        pager.setCurrentPage(page);
        pager.setEveryPage(pagesize);
        pager = this.overdueApiService.selectGroupTaskListPage(pager);
        List<OverdueCstDTO> resultList = (List<OverdueCstDTO>) pager.getResultList();
        if(CollectionUtils.isNotEmpty(resultList)){
            pager.setResultList(OverdueCstVOTransform.toVOList(resultList));
        }
        return pager;
    }

    @Override
    public List<KeyValueVO> getInsCdKeyValueList() {
        List<KeyValueVO> result = null;
        List<FriBaseInfoVO> list = this.getFriBaseInfoList();
        if(CollectionUtils.isNotEmpty(list)){
            result = new ArrayList<>();
            for (FriBaseInfoVO friBaseInfoVO : list) {
                KeyValueVO vo = new KeyValueVO();
                vo.setKey(friBaseInfoVO.getInsCode());
                vo.setValue(friBaseInfoVO.getFundRasInsNm());
                result.add(vo);
            }
        }
        return result;
    }
}
